<script setup>
import { ref, watch } from 'vue';
import { defineProps, defineEmits } from 'vue';

// 接受数据
const props = defineProps({
  category: {
    type: Object,
    required: true
  }
});
//声明触发的事件
const emit = defineEmits()

// 初始化设置
const checkedIds = ref([]);
const allItemIds = [];



// 收集所有的 ID
props.category.resourceList.forEach((resource) => {
  allItemIds.push(resource.id);
  if (resource.selected) {
    checkedIds.value.push(resource.id);
  }
});

// 全选和半选状态的初始值
const checkAll = ref(checkedIds.value.length === allItemIds.length);
const isIndeterminate = ref(checkedIds.value.length > 0 && checkedIds.value.length < allItemIds.length);

const handleCheckAllChange = (val) => {
  checkedIds.value = val ? allItemIds.slice() : [];
  isIndeterminate.value = false;
};

const handleCheckedCitiesChange = (checkedItems) => {
  const checkedCount = checkedItems.length;
  checkAll.value = checkedCount === allItemIds.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < allItemIds.length;
};

// 监听 checkedIds 变化，更新全选和半选状态
watch(checkedIds, (newVal) => {
  const checkedCount = newVal.length;
  checkAll.value = checkedCount === allItemIds.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < allItemIds.length;
  // 发送更新后的 checkedIds 给父组件
  emit("postCheckedIdsRef", { value: newVal });
});


</script>


<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          {{ props.category.name }}
        </el-checkbox>
      </div>
    </template>
    <el-checkbox-group v-model="checkedIds" @change="handleCheckedCitiesChange">
      <el-row>
        <el-col :span="8" v-for="resource in props.category.resourceList" :key="resource.id">
          <el-checkbox :label="resource.id" :value="resource.id">
            {{ resource.name }}
          </el-checkbox>
        </el-col>
      </el-row>
    </el-checkbox-group>
  </el-card>
</template>

<style scoped>
.el-card {
  margin-bottom: 37px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.box-card {
  width: auto;
}
</style>
